package org.blogwu.learn.multithread.chapter3.demo6.v1;

public class ReadThread extends Thread {

    private int ci = -1;

    private static int res = 0;

    public ReadThread(int ci) {
        this.ci = ci;
    }

    @Override
    public void run() {
        long curTime = System.currentTimeMillis();
        while (true) {
            if (ci == 0) {
                //读
                Main.readLock.lock();
                System.out.println(((System.currentTimeMillis() - curTime) / 1000) + "  read start:" + res);
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(((System.currentTimeMillis() - curTime) / 1000) + "  read over:" + res);
                Main.readLock.unlock();
            } else {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 写
                Main.writeLock.lock();
                System.out.println(((System.currentTimeMillis() - curTime) / 1000) + "开始写");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                res = res + 1;
                System.out.println(((System.currentTimeMillis() - curTime) / 1000) + "写完毕");
                Main.writeLock.unlock();
            }

        }
    }

}
